import pytest
import os
import allure
import json
from constant import DATA_PATH

@pytest.hookimpl(tryfirst=True, hookwrapper=True)
def pytest_runtest_makereport(item) -> None:
    '''用例失败截图

    :param _type_ item: 单条用例对象
    '''
    outcome = yield
    rep = outcome.get_result()
    if rep.when == "call" and rep.failed:
        driver = item.cls.driver
        mode = "a" if os.path.exists("failures") else "w"
        with open("failures", mode) as f:
            extra = " (%s)" % item.funcargs["tmpdir"] if "tmpdir" in item.fixturenames else ""
            f.write(rep.nodeid + extra + "\n")
        if hasattr(driver, "get_screenshot_as_png"):
            allure.step('添加失败截图...')
            allure.attach(driver.get_screenshot_as_png(), "失败截图", allure.attachment_type.PNG)


@pytest.fixture()
def read_data():
    '''读取测试用例
    统一整合读取，方便管理，但部分场景操作受限

    :return _type_: _description_
    '''
    file_path = os.path.join(os.getcwd(), DATA_PATH)
    with open(file_path, mode='r', encoding='utf-8') as f:
        return json.loads(f.read())